var regionSelect = $('#region-selection');

var trendingPerRegionChart = $('.chart.trending-per-region');
var trendingPerRegionGenderChart = $('.chart.trending-per-region-gender');
var trendingPerRegionGroupChart = $('.chart.trending-per-region-group');
var trendingPerRegionGroupGenderChart = $('.chart.trending-per-region-group-gender');
var trendingPerLocalityGroupChart = $('.chart.trending-per-locality-group');
var trendingPerLocalityGroupGenderChart = $('.chart.trending-per-locality-group-gender');
var trendingPerLocalityGenderChart = $('.chart.trending-per-locality-gender');

var populateRegionsIntoSelect = function(select) {
	select.html('');
	if (!select.hasClass('disabled')) select.addClass('disabled');

	$.post(app.baseUrl() + 'index.php/references/regionNames').done(function(response) {
		var regions = null;

		try {
			regions = JSON.parse(response);
		}
		catch (ex) {

		}

		if (regions != null &&
			regions != undefined) {
			if (regions.length > 0) {
				for (i = 0; i < regions.length; i++) {
					var region = regions[i];
					select.append('<option value="' + region + '">' + region + '</option>');
				}

				var lastRegion = regions[regions.length - 1];
				select.val(lastRegion);

				trendingPerLocalityGender();

				select.unbind('change');
				select.change(function() {
					trendingPerLocalityGender();
				});
			}
		}
	}).fail(function(response) {

	}).always(function() {
		select.removeClass('disabled');
	});
}

var renderBarSeriesChart = function(chart, title, subtitle, categories, data) {
	if (data != null &&
		data != undefined) {
		chart.highcharts({
            'chart': {
                type: 'bar'
            },
            title: {
                text: title
            },
            subtitle: {
                text: subtitle
            },
            xAxis: {
                'categories': categories,
                title: {
                    text: null
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Count',
                    align: 'high'
                },
                labels: {
                    overflow: 'justify'
                }
            },
            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: true
                    }
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -40,
                y: 100,
                floating: true,
                borderWidth: 1,
                backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor || '#FFFFFF'),
                shadow: true
            },
            credits: {
                enabled: false
            },
            series: data
        });
	}
} ;

var renderPieChart = function(chart, title, data) {
	if (data != undefined &&
		data != null) {
		if (data.length > 0) {
			chart.highcharts({
		        'chart': {
		            type: 'pie',
		            options3d: {
						enabled: true,
		                alpha: 45,
		                beta: 0
		            }
		        },
		        
		        title: {
		            text: title
		        },

		        plotOptions: {
		            pie: {
		                allowPointSelect: true,
		                cursor: 'pointer',
		                depth: 35,
		                dataLabels: {
		                    enabled: true,
		                    format: '{point.name}'
		                }
		            }
		        },
		        
		        series: [{
		            type: 'pie',
		            name: 'Trainees',
		            'data': data 
		        }]
		    });
		}
	}
}

var trendingPerLocalityGender = function() {
	var region = regionSelect.val();

	$.post(app.baseUrl() + 'index.php/trending/perLocalityGender', {
		'region' : region
	}).done(function(response) {
		var data = null;

		try {
			data = JSON.parse(response);
		}
		catch (ex) {

		}

		if (data != null &&
			data != undefined) {
			trendingPerLocalityGenderChart.highcharts({
	            chart: {
	                type: 'bar'
	            },
	            title: {
	                text: 'Brothers and Sisters Attended Per Locality - ' + region
	            },
	            xAxis: {
	                categories: [ 'Brothers', 'Sisters' ]
	            },
	            yAxis: {
	                min: 0,
	                title: {
	                    text: 'Count'
	                }
	            },
	            legend: {
	                reversed: true
	            },
	            plotOptions: {
	                series: {
	                    stacking: 'normal'
	                }
	            },
	            series: data
	        });
		}
	}).fail(function(response) {

	}).always(function() {

	});
};

var trendingPerLocalityGroup = function() {
	$.post(app.baseUrl() + 'index.php/trending/perLocalityGroup').done(function(response) {
		var data = null;

		try {
			data = JSON.parse(response);
		}
		catch (ex) {

		}

		renderPieChart(trendingPerLocalityGroupChart, 'Attending Trainees Per Sub Region', data);
	}).fail(function(response) {

	}).always(function() {

	});
};

var trendingPerLocalityGroupGender = function() {
	$.post(app.baseUrl() + 'index.php/references/localityGroupNames').done(function(response) {
		var localityGroupNames = null;

		try {
			localityGroupNames = JSON.parse(response);
		}
		catch (ex) {

		}

		if (localityGroupNames != null &&
			localityGroupNames != undefined) {
			$.post(app.baseUrl() + 'index.php/trending/perLocalityGroupGender').done(function(webResponse) {
				var data = null;

				try {
					data = JSON.parse(webResponse);
				}
				catch (ex) {

				}

				renderBarSeriesChart(trendingPerLocalityGroupGenderChart, 'Brothers and Sisters Attended Per Sub Region', 'FTTM Batch #', localityGroupNames, data);
			}).fail(function(response) {

			}).always(function() {

			});
		}
	}).fail(function(response) {

	}).always(function() {

	});
};

var trendingPerRegion = function() {
	$.post(app.baseUrl() + 'index.php/trending/perRegion').done(function(response) {
		var data = null;

		try {
			data = JSON.parse(response);
		}
		catch (ex) {

		}

		renderPieChart(trendingPerRegionChart, 'Attending Trainees Per Region', data);
	}).fail(function(response) {
		try {
			console.error(response);
		}
		catch(ex) {

		}
	}).always(function() {

	});
};

var trendingPerRegionGender = function() {
	$.post(app.baseUrl() + 'index.php/references/regionNames').done(function(response) {
		var regions = null;

		try {
			regions = JSON.parse(response);
		}
		catch (ex) {

		}

		if (regions != null &&
			regions != undefined) {
			var genders = [ 'Brothers', 'Sisters' ];
			var current = 0;
			var series = [];

			for (i = 0; i < genders.length; i++) {
				var gender = genders[i];

				$.post(app.baseUrl() + 'index.php/trending/perRegionGender', {
					'gender' : gender
				}).done(function(webResponse) {
					current += 1;

					var data = null;

					try {
						data = JSON.parse(webResponse);
					}
					catch (ex) {

					}

					if (data != null &&
						data != undefined) series.push(data);

					if (current == genders.length) {
						trendingPerRegionGenderChart.highcharts({
				            title: {
				                text: 'Brothers and Sisters Attended Per Region',
				                x: -20
				            },
				            subtitle: {
				                text: 'FTTM Batch #',
				                x: -20
				            },
				            xAxis: {
				                categories: regions
				            },
				            yAxis: {
				            	title: {
				                    text: 'Count'
				                },
				                plotLines: [{
				                    value: 0,
				                    width: 1,
				                    color: '#808080'
				                }]
				            },
				            legend: {
				                layout: 'vertical',
				                align: 'right',
				                verticalAlign: 'middle',
				                borderWidth: 0
				            },
				            'series': series
				        });
					}
				}).fail(function(webResponse) {

				}).always(function() {

				});
			}
		}
	}).fail(function(response) {

	}).done(function() {

	});
};

var trendingPerRegionGroup = function() {
	$.post(app.baseUrl() + 'index.php/trending/perRegionGroup').done(function(response) {
		var data = null;

		try {
			data = JSON.parse(response);
		}
		catch (ex) {

		}

		renderPieChart(trendingPerRegionGroupChart, 'Attending Trainees Per Island Group', data);
	}).fail(function(response) {

	}).always(function() {

	});
};

var trendingPerRegionGroupGender = function() {
	$.post(app.baseUrl() + 'index.php/references/regionGroupNames').done(function(response) {
		var regionGroupNames = null;

		try {
			regionGroupNames = JSON.parse(response);
		}
		catch (ex) {

		}

		if (regionGroupNames != null &&
			regionGroupNames != undefined) {
			$.post(app.baseUrl() + 'index.php/trending/perRegionGroupGender').done(function(webResponse) {
				var data = null;

				try {
					data = JSON.parse(webResponse);
				}
				catch (ex) {

				}

				renderBarSeriesChart(trendingPerRegionGroupGenderChart, 'Brothers and Sisters Attended Per Island Group', 'FTTM Batch #', regionGroupNames, data);
			}).fail(function(response) {

			}).always(function() {

			});
		}
	}).fail(function(response) {

	}).always(function() {

	});
};

$(document).ready(function() {
	populateRegionsIntoSelect(regionSelect);

	trendingPerRegion();
	trendingPerRegionGender();
	trendingPerRegionGroup();
	trendingPerRegionGroupGender();
	trendingPerLocalityGroup();
	trendingPerLocalityGroupGender();
});